import {PlusOutlined} from '@ant-design/icons';
import {Button, message, Input, Drawer} from 'antd';
import React, {useState, useRef, useEffect} from 'react';
import {useIntl, FormattedMessage} from 'umi';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import ProTable, {TableDropdown} from '@ant-design/pro-table';
import {ProFormText, ProFormTextArea} from '@ant-design/pro-form';
import ProDescriptions from '@ant-design/pro-descriptions';
import {updatePrefix, getAllPrefixes, getLRSPrefix, approve, disapprove} from '@/services/doa/irs'
import ReactJson from 'react-json-view'
import ProForm from '@ant-design/pro-form'
import {OrganizationGraph} from '@ant-design/charts';


const PrefixManagement = () => {


  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const intl = useIntl();
  const [showDetail, setShowDetail] = useState(false);
  const actionRef = useRef();
  const info = (msg) => {
    message.info(msg);
  };
  const [currentRow, setCurrentRow] = useState();
  const [prefixes, setPrefixes] = useState([]);
  const [organizations, setOrganizations] = useState({});

  const getAllOrganizations = () => {
    getAllPrefixes().then((response) => {
      if (response?.success) {
        setPrefixes(response.data)
      }
    })
  }

  useEffect(() => {
    getAllOrganizations()
  }, [])


  function ifSon(root, prefix){
    if(root === ""){
      if(prefix.indexOf(".") != -1)
        return false
      return true
    }
    if(!prefix.startsWith(root+"."))
      return false
    prefix = prefix.replace(root+".","")
    return ifSon("",prefix)
  }

  const treeConstruct = (prefix, node, orgs)=>{
    orgs?.map((item) => {
      if(ifSon(prefix, item.prefix)){
        const sonNode = {id:item.prefix, value:{text:item.prefix}, children:[]}
        treeConstruct(item.prefix, sonNode, orgs)
        node.children.push(sonNode)
      }
    })
  }

  useEffect(() => {
    actionRef.current.reloadAndRest()

    getLRSPrefix().then((response) => {
      const prefix = response.data
      const data = {
        id: prefix,
        value: {
          text: prefix
        },
        children: []
      }

      treeConstruct(prefix,data, prefixes)

      // data.children = prefixes.map((item) => {
      //   return {id: item.prefix, value: {text: item.prefix + "（" + item.status +"）"}}
      // })


      setOrganizations(data)
    })


  }, [prefixes])

  const columns = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '分配前缀',
      dataIndex: 'prefix',
      valueType: 'text',
      copyable: true,
      ellipsis: true,
      search: false,
    },
    {
      title: '所有者标识',
      dataIndex: 'doi',
      valueType: 'text',
      editable: false,
      copyable: true,
      ellipsis: true,
      search: false,
    },
    {
      title: '公钥',
      dataIndex: 'jwkKey',
      valueType: 'text',
      copyable: true,
      ellipsis: true,
      search: false,
    },
    {
      title: '所属组织名称',
      dataIndex: 'name',
      valueType: 'text',
      copyable: true,
      ellipsis: true,
      search: false,
    },
    {
      title: '协议版本号',
      dataIndex: 'protocol',
      valueType: 'text',
      copyable: true,
      ellipsis: true,
      search: false,
    },
    {
      title: '服务地址',
      dataIndex: 'serviceAddress',
      valueType: 'text',
      copyable: true,
      ellipsis: true,
      search: false,
    },
    {
      title: '状态',
      dataIndex: 'status',
      editable: false,
      search: false,
      filters: true,
      onFilter: true,
      valueType: 'select',
      valueEnum: {
        closed: {
          text: '停止',
          status: '停止',
        },
        running: {
          text: '运行',
          status: '运行',
          disabled: true,
        },
        pending: {
          text: '待审核',
          status: '待审批',
        },
        approved: {
          text: '审核通过',
          status: '审核通过',
        }
      }
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => {
        if (record.status !== '审核通过') {
          return [
            <a
              key="editable"
              onClick={() => {
                action?.startEditable?.(record.doi);
              }}
            >
              编辑
            </a>,
            <a key="view"
               onClick={() => {
                 setCurrentRow(record);
                 setShowDetail(true);
               }}>
              查看详情
            </a>,
            <a key="approve"
               onClick={() => {
                 console.log(record)
                 approve(record).then(r => {
                   console.log(r.data)
                   if (r.data === "保存成功") {
                     info("审核通过")
                     record.status = "审核通过"
                     actionRef.current.reloadAndRest()
                   }
                 });
               }}>
              通过
            </a>
          ]
        } else {
          return [
            <a
              key="editable"
              onClick={() => {
                action?.startEditable?.(record.doi);
              }}
            >
              编辑
            </a>,
            <a key="view"
               onClick={() => {
                 setCurrentRow(record);
                 setShowDetail(true);
               }}>
              查看详情
            </a>,
            <a key="disapprove"
               style={{"color":"#F00"}}
               onClick={() => {
                 console.log(record)
                 disapprove(record).then(r => {
                   console.log(r.data)
                   if (r.data === "保存成功") {
                     record.status = "待审核"
                     info("撤销成功")
                     actionRef.current.reloadAndRest()
                   }
                 });
               }}>
              撤销
            </a>
          ]
        }
      },
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle={intl.formatMessage({
          id: 'pages.grs.prefix.management.table.title',
          defaultMessage: '前缀列表',
        })}
        actionRef={actionRef}
        rowKey="doi"
        toolbar={{
          search: {
            onSearch: (value) => {
              console.log(value);
            },
          },
          actions: [
            <Button key="list" type="primary">
              查询
            </Button>,
          ],
        }}
        editable={{
          type: 'multiple',
          onSave: async (rowKey, data, row) => {
            //data是修改后的数据，row是原来的数据
            console.log(rowKey, data, row);
            updatePrefix(data).then((response) => {
              if (response?.success == true) {
                info("修改成功")
              } else {
                info("修改失败")
              }
            })
          },
        }}
        search={false}
        options={{
          search: true,
        }}
        toolBarRender={() => []}
        request={async (params, sort, filter) => {
          return Promise.resolve({
            data: prefixes,
            success: true,
          });
        }}
        columns={columns}
      />

      <OrganizationGraph data={organizations} behaviors={['drag-canvas', 'zoom-canvas', 'drag-node']}/>

      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions
            column={1}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.doi,
            }}
            columns={columns}
          />
        )}
        <ReactJson src={currentRow}/>
      </Drawer>
    </PageContainer>
  );
};

export default PrefixManagement;
